﻿using System;
using System.Linq;
using VideoSeller.Business.Data;

namespace VideoSeller.Business.Models
{
	public class OfflineRatingModel : Repository<OfflineRating>
	{
		private readonly SettingsModel _settingsModel;

		public OfflineRatingModel(SettingsModel settingsModel)
		{
			_settingsModel = settingsModel;
		}

		public int GetRate(int onlineContentId, bool positive)
		{
			if (positive)
			{
				return Math.Abs(Table.Where(x => x.OfflineContentId == onlineContentId && x.Value > 0).Sum(x => x.Value));
			}

			return Math.Abs(Table.Where(x => x.OfflineContentId == onlineContentId && x.Value < 0).Sum(x => x.Value));
		}

		public int Rate(Guid userId, int offlineContentId, bool positive, string comment)
		{
			var setting = _settingsModel.GetSetting("RatingStep");
			var ratingStep = setting != null ? short.Parse(setting.Value) : (short) 5;
			var rating = new OfflineRating
				{
					UserId = userId,
					OfflineContentId = offlineContentId,
					Comment = comment,
					CreateTime = DateTime.Now,
					Value = positive ? ratingStep : (short)-ratingStep
				};

			Insert(rating);

			return GetRate(offlineContentId, positive);
		}
	}
}